package com.axjy.yycg.web;

import com.axjy.yycg.pojo.Role;
import com.axjy.yycg.pojo.Sysuser;
import com.axjy.yycg.service.RoleService;
import com.axjy.yycg.service.SysuserService;
import com.axjy.yycg.util.Log;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * User: ZhangXuanWei
 * Time: 2018/3/20 21:09
 * Description:
 */
@RestController
@RequestMapping("/sys/js")
public class RoleHandler {

    private String msg;
    @Resource
    private RoleService roleService;

    @Resource
    private SysuserService sysuserService;

    /**
     * 查询所有角色
     * @return
     */
    @GetMapping("/list")
    public List<Role> list(){
        return roleService.list();
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/add")
    public String addRole(Role role){
        role.setModifyTime(LocalDateTime.now());
        try {
            roleService.addRole(role);
            msg="角色添加成功！";
        }catch (RuntimeException ex){
            msg="角色添加失败！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }


    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @PostMapping("/batchDel")
    public String batchDel(Integer[] ids){
        Sysuser sysuser=null;
        try {
            for(Integer id:ids){
                sysuser=sysuserService.findUserByRoleId(id);
            }
            System.out.println("sysuser=====>"+sysuser);
            if(sysuser==null){
                roleService.batchDel(ids);
                msg="删除成功！";
            }

        }catch (RuntimeException ex){
            msg="对不起，该角色已被使用，不能删除!" ;
            Log.logger.error(msg,ex);
        }
        return msg;
    }

    @PostMapping("/updateState")
    public String updateState(Integer id,Integer state){
        try {
            roleService.updateState(id,state);
            if(state==1){
                msg="角色已被禁用";
            }else {
                msg="角色已启用";
            }
        }catch (RuntimeException ex){
            msg="操作失败！";
        }
        return msg;
    }

    @PostMapping("/updateName")
    public String updateName(Integer id,String name){
        try {
            roleService.updateName(id,name);
            msg="修改成功！";
        }catch (RuntimeException ex){
            msg="修改失败！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }
}
